import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useAuthStore } from '@/store/useAuthStore'
import { ResponseData } from './types'
import { message } from 'antd'

class HttpRequest {
  // axios 实例
  private instance: AxiosInstance;
  
  constructor() {
    this.instance = axios.create({
      baseURL: this.getBaseURL(),
      timeout: 10000, // 10秒超时
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    this.setupInterceptors();
  }

  // 获取基础URL
  public getBaseURL(): string {
    if (import.meta.env.MODE === 'production') {
      return '/'
      
    }
    return 'http://127.0.0.1:8000'
    
  }

  // 获取完整的头像URL
  public getAvatarUrl(path: string): string {

    if(import.meta.env.MODE === 'development'){
      return `${this.getBaseURL()}/data${path}`;
    }
    return path;    
  }

  // 设置拦截器
  private setupInterceptors(): void {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = useAuthStore.getState().token
        if (token) {
          config.headers.Authorization = `Token ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response
      },
      (error) => {
        // if (error.response?.status === 401) {
        //   useAuthStore.getState().clearAuth()
        //   window.location.href = '/login'
        // }
        if (error.response?.data?.code=== 401) {
          useAuthStore.getState().clearAuth()
          window.location.href = '/login'
        }
        // 处理错误信息
        if (error.response?.data?.data) {
          // 如果是对象形式的错误信息，将所有错误信息合并
          const errors = error.response.data.data;
          if (typeof errors === 'object') {
            const errorMessages = Object.values(errors).flat();
            message.error(errorMessages.join(', '));
          } else {
            // 如果是字符串形式的错误信息
            message.error(errors);
          }
        } else if (error.response?.data?.message) {
          // 美化错误信息显示
          let errorMessage = error.response.data.message;
          
          // 检查是否是Django REST framework的错误格式
          if (typeof errorMessage === 'string' && errorMessage.includes('ErrorDetail')) {
            try {
              // 尝试解析 ErrorDetail(string='...', code='...') 格式
              const match = errorMessage.match(/string='([^']+)'/);
              if (match) {
                errorMessage = match[1];
              } else {
                // 尝试解析其他可能的格式
                const jsonMatch = errorMessage.match(/\{[^}]+\}/);
                if (jsonMatch) {
                  try {
                    const parsed = JSON.parse(jsonMatch[0]);
                    if (parsed.string) {
                      errorMessage = parsed.string;
                    }
                  } catch (parseError) {
                    // 如果解析失败，尝试提取引号中的内容
                    const simpleMatch = errorMessage.match(/'([^']+)'/);
                    if (simpleMatch) {
                      errorMessage = simpleMatch[1];
                    }
                  }
                }
              }
            } catch (parseError) {
              console.warn('解析错误信息失败:', parseError);
              // 如果解析失败，使用默认错误信息
              errorMessage = '操作失败，请稍后重试';
            }
          }
          
          message.error(errorMessage);
        } else {
          // 默认错误信息
          message.error('操作失败，请稍后重试');
        }
        return Promise.reject(error)
      }
    )
  }

  // HTTP 请求方法
  public async get<T = any>(url: string, config?: AxiosRequestConfig) {
    return this.instance.get<ResponseData<T>>(url, config)
  }

  public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    return this.instance.post<ResponseData<T>>(url, data, config)
  }

  public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    return this.instance.put<ResponseData<T>>(url, data, config)
  }

  public async delete<T = any>(url: string, config?: AxiosRequestConfig) {
    return this.instance.delete<ResponseData<T>>(url, config)
  }

  public async patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    return this.instance.patch<ResponseData<T>>(url, data, config)
  }
}

// 创建并导出单例
const request = new HttpRequest()
export default request 